package com.browser.history;

import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;

@Data
public class HistoryManager {
    private static final Logger logger = LoggerFactory.getLogger(HistoryManager.class);
    private final List<HistoryEntry> history;
    private int currentIndex;

    public HistoryManager() {
        this.history = new ArrayList<>();
        this.currentIndex = -1;
    }

    public void addEntry(String url, String title) {
        logger.debug("Adding history entry: {} - {}", title, url);
        
        // 移除当前位置之后的所有记录
        while (history.size() > currentIndex + 1) {
            history.remove(history.size() - 1);
        }

        history.add(new HistoryEntry(url, title, System.currentTimeMillis()));
        currentIndex++;
    }

    public HistoryEntry getCurrentEntry() {
        if (currentIndex >= 0 && currentIndex < history.size()) {
            return history.get(currentIndex);
        }
        return null;
    }

    public boolean canGoBack() {
        return currentIndex > 0;
    }

    public boolean canGoForward() {
        return currentIndex < history.size() - 1;
    }

    public HistoryEntry goBack() {
        if (canGoBack()) {
            return history.get(--currentIndex);
        }
        return null;
    }

    public HistoryEntry goForward() {
        if (canGoForward()) {
            return history.get(++currentIndex);
        }
        return null;
    }

    public void clearHistory() {
        logger.info("Clearing browsing history");
        history.clear();
        currentIndex = -1;
    }

    public List<HistoryEntry> getHistory() {
        return new ArrayList<>(history);
    }
} 